/* eslint-disable */
<template>
  <div class="woFlowPage">
    <div class="editBox">
      <q-btn
        v-if="!editMode"
        label="编辑工序流程"
        color="blue-5"
        class="editBtn"
        @click="editMode = !editMode"
      >
        <q-icon name="fa-solid fa-pen" class="editSVG" />
      </q-btn>
      <div v-else>
        <q-btn
          label="取消"
          color="grey-8"
          class="cancelBtn"
          @click="cancelChanges()"
        />
        <q-btn
          label="储存工序流程"
          color="blue-5"
          class="saveBtn"
          @click="saveChanges()"
        >
          <q-icon name="fa-solid fa-floppy-disk" class="saveSVG" />
        </q-btn>
      </div>
    </div>
    <div class="routeTableBox">
      <q-table
        class="routeTable"
        flat
        bordered
        table-header-class="bg-grey-8 text-grey-1"
        :rows="editrows"
        :columns="rtcolumns"
        row-key="stepNo"
        :loading="loading"
        :pagination="{ rowsPerPage: 10 }"

      >
        <template v-slot:body="props">
          <q-tr
            :props="props"
            :class="
              props.row.status === 3
                ? 'status-complete'
                : props.row.status === 2
                ? 'status-inprogress'
                : ' '
            "
          >
            <q-td key="stepNo" :props="props">
              <q-icon
                v-show="editMode && props.row.status === 1"
                name="fa-regular fa-square-minus"
                class="removeSVG"
                @click="removeRow(props.rowIndex)"
              />
              {{ props.row.stepNo }}
              <q-icon
                v-show="canMoveUp(props.rowIndex, props.row.status)"
                name="fa-solid fa-arrow-up"
                class="upDownSVG"
                @click="rowUp(props.rowIndex)"
              />
              <q-icon
                v-show="canMoveDown(props.rowIndex, props.row.status)"
                name="fa-solid fa-arrow-down"
                class="upDownSVG"
                @click="rowDown(props.rowIndex)"
              />
            </q-td>
            <q-td key="routeName" :props="props">
              <span v-if="props.row.routeName">{{
                props.row.routeName.label
              }}</span>
              <q-popup-edit
                v-model="props.row.routeName"
                auto-save
                v-slot="scope"
                :disable="!editMode || props.row.status != 1"
              >
                <q-select
                  v-model="scope.value"
                  :options="routeNameOpt"
                  @change="scope.set"
                />
              </q-popup-edit>
            </q-td>
            <q-td key="qty" :props="props">
              {{ props.row.qty }}
              <q-popup-edit
                v-model="props.row.qty"
                auto-save
                v-slot="scope"
                :disable="!editMode || props.row.status != 1"
              >
                <q-input
                  type="number"
                  v-model="scope.value"
                  dense
                  min="1"
                  autofocus
                  @keyup.enter="scope.set"
                />
              </q-popup-edit>
            </q-td>
            <q-td key="difficulty" :props="props">
              <div class="text-pre-wrap">
                <span v-if="props.row.difficulty">{{
                  props.row.difficulty.label
                }}</span>
              </div>
              <q-popup-edit
                v-model="props.row.difficulty"
                auto-save
                v-slot="scope"
                :disable="!editMode || props.row.status != 1"
              >
                <q-select
                  v-model="scope.value"
                  :options="difficultyOpt"
                  @change="scope.set"
                />
              </q-popup-edit>
            </q-td>
            <q-td key="psName" :props="props">
              <div class="text-pre-wrap">
                <span v-if="props.row.psName && isStoneSetting(props.row.routeName)">{{
                  props.row.psName.label  ? props.row.psName.label : ''
                }}</span>
                <span v-else-if="isStoneSetting(props.row.routeName)">
                  {{''}}
                </span>
                <span v-else>
                  {{'不适用'}}
                </span>

              </div>
              <q-popup-edit
                v-model="props.row.psName"
                auto-save
                v-slot="scope"
                :disable="
                  !(
                    editMode &&
                    isStoneSetting(props.row.routeName) &&
                    props.row.status == 1
                  )
                "
              >
                <q-select
                  v-model="scope.value"
                  :options="psNameOpt"
                  @change="scope.set"
                />
              </q-popup-edit>
            </q-td>
            <q-td key="ssName" :props="props">
              <div class="text-pre-wrap">
                <span v-if="props.row.ssName  && isStoneSetting(props.row.routeName)">{{
                  props.row.ssName.label
                }}</span>
                 <span v-else-if="isStoneSetting(props.row.routeName)">
                  {{''}}
                </span>
                    <span v-else>
                  {{'不适用'}}
                </span>
              </div>
              <q-popup-edit
                v-model="props.row.ssName"
                auto-save
                v-slot="scope"
                :disable="
                  !(
                    editMode &&
                    isStoneSetting(props.row.routeName) &&
                    props.row.status == 1
                  )
                "
              >
                <q-select
                  v-model="scope.value"
                  :options="ssNameOpt"
                  @change="scope.set"
                />
              </q-popup-edit>
            </q-td>
            <q-td key="consumePercent" :props="props">
              {{ props.row.consumePercent }}
              <q-popup-edit
                v-model="props.row.consumePercent"
                auto-save
                v-slot="scope"
                :disable="!editMode || props.row.status != 1"
              >
                <q-input type="number" min="1" v-model="scope.value" dense autofocus />
              </q-popup-edit>
            </q-td>
            <q-td key="workfee" :props="props">
              {{ props.row.workfee }}
              <q-popup-edit
                v-model="props.row.workfee"
                auto-save
                v-slot="scope"
                :disable="!editMode || props.row.status != 1"
              >
                <q-input type="number" min="1" v-model="scope.value" dense autofocus />
              </q-popup-edit>
            </q-td>
            <q-td key="addRow" :props="props">
              <q-icon
                v-show="
                  editMode &&
                  (props.row.status !== 3 ||
                    (props.row.status === 3 && props.rowIndex + 1 === last_row))
                "
                name="fa-regular fa-square-plus"
                class="addSVG"
                @click="addRow(props.rowIndex)"
              />
            </q-td>
          </q-tr>
        </template>
        <template v-slot:loading>
          <q-inner-loading showing color="primary" />
        </template>
      </q-table>
    </div>
  </div>
</template>

<script setup>
import { useWoRoutingStore } from "src/stores/modules/woroutinghistStore";
import { ref, toRaw } from "vue";
import { useQuasar } from "quasar";

console.log("Initializing wodetails page...");

const $q = useQuasar();
let routingTb = [];
const woRoutingStore = useWoRoutingStore();
routingTb = toRaw(woRoutingStore.getOrderRoutingTable);
console.log("routingTb: ", routingTb);

const orderRoute = woRoutingStore.order_route;

const routeNameOpt = woRoutingStore.opt_flow;
const difficultyOpt = woRoutingStore.opt_difficulty;
const psNameOpt = woRoutingStore.opt_stone_mount_list;
const ssNameOpt = woRoutingStore.opt_stone_mount_list;

let originalRoutingTb = null;
let rtcolumns = [];
let rtrows = [];
let editrows = [];
const last_row = ref(0);
const loading = ref(false);
const editMode = ref(false); // Edit Mode

if (routingTb.length > 0) {
  originalRoutingTb = [...JSON.parse(JSON.stringify(routingTb))];
  console.log("originalRoutingTb: ", originalRoutingTb);
  last_row.value = originalRoutingTb.length;
  console.log("----------------------last_row: ", last_row.value);

  // Route Table columns(rtcolumns) & rows(rtrows)
  rtcolumns = [
    {
      name: "stepNo",
      required: true,
      label: "项目",
      align: "center",
      field: (row) => row.stepNo,
      format: (val) => `${val}`,
      sortable: false,
    },
    {
      name: "routeName",
      align: "center",
      label: "Routing名称",
      field: "routeName",
      sortable: false,
    },
    {
      name: "qty",
      align: "center",
      label: "分件数量",
      field: "qty",
      sortable: false,
    },
    {
      name: "difficulty",
      align: "center",
      label: "难易程度",
      field: "difficulty",
      sortable: false,
    },
    {
      name: "psName",
      align: "center",
      label: "镶法技术(主)",
      field: "psName",
      sortable: false,
    },
    {
      name: "ssName",
      align: "center",
      label: "镶法技术(次)",
      field: "ssName",
      sortable: false,
    },
    {
      name: "consumePercent",
      align: "center",
      label: "给耗(%)",
      field: "consumePercent",
      sortable: false,
    },
    {
      name: "workfee",
      align: "center",
      label: "工人工费(元)",
      field: "workfee",
      sortable: false,
    },
    {
      name: "addRow",
      align: "center",
      label: "新增步骤",
      field: "addRow",
      sortable: false,
    },
  ];
  rtrows = [...JSON.parse(JSON.stringify(originalRoutingTb))];
  editrows = ref([]);
  editrows.value = [...JSON.parse(JSON.stringify(rtrows))];
} else {
  console.log("Failed to load routing table");
}

// Function: Remove Row
const removeRow = (rowIndex) => {
  editrows.value = [
    ...editrows.value.slice(0, rowIndex),
    ...editrows.value.slice(rowIndex + 1),
  ];
  for (let i = rowIndex; i < editrows.value.length; i++) {
    editrows.value[i].stepNo = "步骤 " + (i + 1);
  }
  console.log(editrows.value);
};

// Function: Add Row
const addRow = (rowIndex) => {
  const newRowIndex = rowIndex + 1;
  const newRowStepNo = newRowIndex + 1;
  const newRow = {
    stepNo: "步骤 " + newRowStepNo,
    routeName: null,
    qty: null,
    difficulty: null,
    psName: null,
    ssName: null,
    consumePercent: null,
    workfee: null,
    status: 1,
    pk: null,
    order_route: orderRoute,
  };
  editrows.value = [
    ...editrows.value.slice(0, rowIndex + 1),
    newRow,
    ...editrows.value.slice(rowIndex + 1),
  ];
  for (let i = newRowIndex + 1; i < editrows.value.length; i++) {
    editrows.value[i].stepNo = "步骤 " + (i + 1);
  }
};

// Function: rowUp
const rowUp = (rowIndex) => {
  if (rowIndex > 0) {
    console.log("cur rowIndex: ", rowIndex);
    const preIndex = rowIndex - 1;
    console.log("prev rowIndex: ", preIndex);

    editrows.value[rowIndex].stepNo = "步骤 " + (preIndex + 1);
    editrows.value[preIndex].stepNo = "步骤 " + (rowIndex + 1);

    const temprev = editrows.value[preIndex];
    console.log("temprev: ", temprev);

    editrows.value[preIndex] = editrows.value[rowIndex];
    editrows.value[rowIndex] = temprev;
  } else {
    console.log("already on the top");
  }
};

// Function: canMoveup
const canMoveUp = (rowIdx, status) => {
  if (editMode && status === 1 && rowIdx > 0) {
    let prev_row_status = editrows.value[rowIdx - 1].status;
    if (prev_row_status === 1) {
      return true;
    }
  }
  return false;
};

// Function: canMovedown
const canMoveDown = (rowIdx, status) => {
  if (editMode && status === 1 && rowIdx < editrows.value.length - 1) {
    let post_row_status = editrows.value[rowIdx + 1].status;
    if (post_row_status === 1) {
      return true;
    }
  }
  return false;
};

// Function: rowDown
const rowDown = (rowIndex) => {
  if (rowIndex < editrows.value.length - 1) {
    const postIndex = rowIndex + 1;

    editrows.value[rowIndex].stepNo = "步骤 " + (postIndex + 1);
    editrows.value[postIndex].stepNo = "步骤 " + (rowIndex + 1);

    const tempost = editrows.value[postIndex];

    editrows.value[postIndex] = editrows.value[rowIndex];
    editrows.value[rowIndex] = tempost;
  } else {
    // console.log('already the bottom la')
  }
};

const isStoneSetting = (props) => {
  if (props) {
    return props.label === "镶石";
  }
  return false;
};

// Function: Save Changes
const saveChanges = async () => {
  const check_flow = editrows.value.find(i=>i.routeName==null)
  if (check_flow){
    $q.notify({
      type: "negative",
      textColor: "white",
      message: "Routing名称不能空白 !",
      timeout: 2000,
      position: "center",
    });
    return
  }
  const newrow = [...JSON.parse(JSON.stringify(editrows.value))];
  const res = await woRoutingStore.saveRoutingTable(newrow, woRoutingStore.order_no);
  if (res) {
    console.log("success");
    rtrows = [...JSON.parse(JSON.stringify(newrow))];
    console.log("save!");
    $q.notify({
      type: "positive",
      textColor: "white",
      message: "成功!",
      timeout: 2000,
      position: "center",
    });
    editMode.value = false;
  } else {
    console.log("failed");
    $q.notify({
      type: "negative",
      textColor: "white",
      message: "错误发生 !",
      timeout: 2000,
      position: "center",
    });
  }
};

// Function: Cancel Changes
const cancelChanges = () => {
  editrows.value = [...JSON.parse(JSON.stringify(rtrows))];
  editMode.value = false;
};
</script>

<style lang="scss" scoped>
.woFlowPage {
  width: 95%;
  margin-left: auto;
  margin-right: auto;
  margin-top: 20px;
  .editBox {
    width: 100%;
    text-align: right;
    .editBtn {
      font-size: 1rem;
    }
    .cancelBtn {
      font-size: 1rem;
      margin-right: 10px;
    }
    .saveBtn {
      font-size: 1rem;
    }
    .editSVG,
    .cancelSVG,
    .saveSVG {
      margin-left: 5px;
      font-size: 1rem;
    }
  }
  .routeTableBox {
    margin-top: 20px;
    font-size: 1.2rem;
    width: 100%;
    overflow: auto;
    .routeTable {
      background-color: white;
      width: 100%;
      border-collapse: collapse;
      border-radius: 5px;
      text-align: center;
      border: 1px solid #a1a1a1;
      thead {
        background-color: #e0e0e0;
        .flowStep {
          width: 100%;
          padding-left: 3px;
          padding-right: 3px;
          font-weight: bold;
          border-width: 0px;
        }
      }
      tbody {
        td {
          padding-top: 5px;
          padding-bottom: 5px;
        }
      }
      th,
      td {
        border: 1px solid #a1a1a1;
      }
      .removeSVG {
        color: red;
        margin-right: 10px;
      }
      .addSVG {
        color: #4436d0;
      }
      .upDownSVG {
        color: #838383;
        font-size: 1rem;
      }
      .removeSVG,
      .addSVG {
        font-size: 1.5rem;
      }
    }
    // .status-open {
    // }
    .status-inprogress {
      background-color: #ffe588;
    }
    .status-complete {
      background-color: #8fd896;
    }
  }
}
</style>
